package com.demo.gulimall.order.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.demo.gulimall.common.utils.R;
import com.demo.gulimall.order.config.AlipayTemplate;
import com.demo.gulimall.order.service.OrderService;
import com.demo.gulimall.order.vo.PayAsyncVo;
import com.demo.gulimall.order.vo.PayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Chen Yuan
 * @create 2023-08-03  16:07
 */
@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController {

	@Autowired
	private AlipayTemplate alipayTemplate;

	@Autowired
	private OrderService orderService;


	// 订单支付
	@GetMapping("/payOrder")
	public R payOrder(String orderSn) throws AlipayApiException {
		PayVo payVo = orderService.getOrderPay(orderSn);

		String payRes = alipayTemplate.pay(payVo);

		log.info("--> 支付结果:{}", payRes);

		return R.ok();
	}



	// 处理阿里支付异步回调
	@PostMapping("/payed/notify")
	public String handleAlipayed(PayAsyncVo asyncVo, HttpServletRequest request) throws AlipayApiException {
		log.info("--> 支付回调 - 参数:{}", asyncVo);

		// 验证数据是否被篡改
		Map<String, String> params = new HashMap<>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (String name : requestParams.keySet()) {
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		//调用SDK验证签名
		boolean check = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(),
				alipayTemplate.getCharset(), alipayTemplate.getSign_type());

		if (check){
			// 签名验证成功, 处理支付结果
			orderService.handlePayResult(asyncVo);
		}else {
			// 验证失败
			return "error";
		}

		return "success";
	}
}
